<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 * 用户相关接口
 * @author Calvin<hongbinfu@163.com>
 * @readme  :返回结果请使用common_response
 * @help    :具体用法请参考https://github.com/chriskacerguis/codeigniter-restserver
 * @other   :
 *          GET ---  $this->get();
 *          POST --- $this->post();
 *          PUT --- $this->put();
 *         DELETE --- $this->delete();
 */
require(APPPATH.'libraries/Mobile_Controller.php');
class User_center extends Mobile_Controller
{
    private $_find_pwd_code = "__FIND_PWD_CODE__";
    private $_find_pwd_user = "__FIND_PWD_USER__";

    public function __construct() {
        parent::__construct();
        $services = array(
            'register_service',
            'login_service',
            'user_verify_service',
            'user_info_service'
        );
        $this->load->service($services);
        $this->load->library("form_validation");
        $this->config->load("form_validation");
    }


    public function login_status_get(){
        $this->load->service('login_service');
        $user_info = $this->login_service->is_login();
        if ($user_info === FALSE) {
            return $this->common_response($this->login_service);
        } else {
            $space = $this->user_info_service->get_format_space($user_info['id']);
            $data=array(
                "name"=>$this->login_service->get_show_name(),
                "space"=>$space,
                "avatar"=>$user_info['image']
            );
            return $this->common_response(0,NULL,array("data"=>$data));
        }
    }

    /**
     * ::用户注册
     * (只能注册手机号码)
     */
    public function register_post()
    {
        //获取账号，密码，以及验证码。
        $account = trim($this->input->post('account'));
        $password = $this->input->post('password',TRUE);
        $sms_vcode = $this->input->post("code",TRUE);


        //检查账号是否已经存，正在被使用中。。。正在使用则返回true
        $phone_valid = $this->user_verify_service->check_user_by_phone($account);
        //$email_valid = $this->user_verify_service->check_user_by_email($account);


        //检查输入的手机或者邮箱是否合法
        $phone_check = $this->form_validation->valid_mobile_phone($account);
        //$email_check = $this->form_validation->valid_email($account);



        /*if(!$phone_check && !$email_check)
        {
            return $this->common_response(1003);
        }*/

        $new_pwd_valid=$this->form_validation->new_valid_password($password);
        //判断密码是否符合
        if($new_pwd_valid !=0)
        {
            return $this->common_response($new_pwd_valid);
        }

        if($phone_check)
        {
            if ($phone_valid)
            {
                //如果输入的手机号码存在，返回错误代码5009
                return $this->common_response(5009);
            }
            //检查输入的短信验证码是否正确
            if(! $this->user_verify_service->check_sms_code($sms_vcode, $account, User_verify_service::PROCESS_REGISTER, TRUE))
            {
                return $this->common_response($this->user_verify_service);
            }
            //通过手机号码来注册的账号。
            $register= $this->register_service->register_by_phone($account, $password);
        }
        else
        {

            return $this->common_response(1003);
        }
       /* else
        {
            if($email_valid)
            {
                //如果输入的邮箱地址存在，返回错误代码5001
                return $this->common_response(5001);
            }
            //检查邮箱验证码是否正确
            if(!$this->user_verify_service->check_email_verify_code($sms_vcode, $account,User_verify_service::PROCESS_REGISTER,FALSE))
            {
                return $this->common_response($this->user_verify_service);
            }
            //通过邮箱来注册账号
            $register= $this->register_service->app_register_by_email($account, $password);
        }*/


        if ($register !== FALSE)
        {
            $this->register_service->delete_register_log();
            $this->login_service->unset_tryout();
            //登录
            $this->login_service->login_by_uid($this->register_service->get_register_uid());
            return $this->common_response(0);
        }
        else
        {
            return $this->common_response($this->register_service);
        }
        //}
    }

    /**
     * ::用户注册::发送短信验证码
     * @return array
     *
     */
    public function register_sms_code_post()
    {
        $this->form_validation->set_rules('account','', 'required|valid_mobile_phone');
        //获取账号
        $account = trim($this->input->post("account",TRUE));
        //检查输入的手机或者邮箱是否合法,合法则返回true
        if( $this->form_validation->valid_mobile_phone($account))
        {   //是否已存在
            if ($this->user_verify_service->check_user_by_phone($account))
            {
                return $this->common_response(5009);
            }
            $send = $this->user_verify_service->send_sms($account, User_verify_service::PROCESS_REGISTER);
        }
        else
        {
            return $this->common_response(1003);
        }

        if ($send !== FALSE)
        {
            return $this->common_response(0);
        }
        else
        {
            return $this->common_response($this->user_verify_service);
        }
    }

    /**
     * ::登录
     *
     * */
    public function login_post()
    {

        if ($this->session->has_userdata($this->_find_pwd_user))
        {
            $array_items = array($this->_find_pwd_code, $this->_find_pwd_user);
            $this->session->unset_userdata($array_items);
        }
        //获取账号
        $account = trim($this->input->post('account',TRUE));
        //检查合法性
        $phone_valid = $this->form_validation->valid_mobile_phone($account);
        $email_valid = $this->form_validation->valid_email($account);

        if( ! $account || !( $email_valid || $phone_valid))
        {
            return $this->common_response(1003);
        }
        //获取密码
        $password = trim($this->input->post('password',TRUE));

        if (empty($password))
        {
            return $this->common_response(1003);
        }


        $user = $email_valid ? $this->login_service->check_login_by_email($account, $password):
            $this->login_service->check_login_by_phone($account, $password);

        if ($user !== FALSE)
        {
            $this->login_service->login_by_data($user,0,0);
            return $this->common_response(0);
        }
        else
        {
            $error = $this->login_service->get_error();
            $this->login_service->add_login_error_log();
            $extra = array();
            //显示验证码
            if ($error['code'] == 5002 && $this->login_service->vcode_required())
            {
                $extra['show_vcode'] = true;
            }
            return $this->common_response($this->login_service,NULL,$extra,FALSE);
        }
    }



    /**
     * ::找回密码::发送验证码
     * (测试发送邮件成功(发送验证码到邮箱))
     */
    public function find_password_sms_code_post() {
        $account = $this->input->post('account',TRUE);
        if (empty($account))
        {
            return $this->common_response(1003);
        }

        //验证是否为邮箱，返回true | false
        $valid_email = $this->form_validation->valid_email($account);
        //验证是否为手机号，返回true | false
        $valid_mobile = $this->form_validation->valid_mobile_phone($account);

        //既不为手机号也不为邮箱，则返回错误代码1003
        if (! $valid_email && ! $valid_mobile)
        {
            return $this->common_response(1003);
        }
        //验证账号是否存在
        if ($valid_mobile)
        {
            $check_user = $this->user_verify_service->check_user_by_phone($account);
        }
        else
        {
            $check_user = $this->user_verify_service->check_user_by_email($account);
        }

        //如果账号不存在
        if ($check_user === FALSE)
        {
            return $this->common_response($this->user_verify_service);
        }

        //如果输入的是手机号码
        if ($valid_mobile)
        {
            $send = $this->user_verify_service->send_sms($account, User_verify_service::PROCESS_FIND_PASSWORD);
        }
        //如果输入的是邮箱地址
        else
        {
            $send = $this->user_verify_service->send_email($account,User_verify_service::PROCESS_FIND_PASSWORD);
        }
        //判断发送状态
        if ($send)
        {
            $user_session = array(
                'type' => $valid_mobile ? 2 : 1,
                'account' => $account
            );
            //session记录用户信息
            $this->session->set_userdata($this->_find_pwd_user, $user_session);
            return $this->common_response(0);
        }
        else
        {
            return $this->common_response($this->user_verify_service);
        }
    }

    /**
     * ::找回密码::提交获取到的验证码
     * (测试输入验证码之能正确记录session数据)
     */
    public function find_password_valid_post()
    {
        $this->form_validation->set_rules('code','', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            return $this->common_response(1003);
        }
        else
        {
            $code = trim($this->input->post('code',TRUE));

            if (! $this->session->has_userdata($this->_find_pwd_user))
            {
                return $this->common_response(1008);
            }

            $my_session = $this->session->userdata($this->_find_pwd_user);
            //type=1为邮箱验证
            if ($my_session['type'] == 1)
            {
                //检查 验证码是否正确
                $check = $this->user_verify_service->check_email_verify_code($code, $my_session['account'],User_verify_service::PROCESS_FIND_PASSWORD,FALSE,FALSE);
            }
            else
            {
                $check = $this->user_verify_service->check_sms_code($code, $my_session['account'], User_verify_service::PROCESS_FIND_PASSWORD, FALSE);
            }

            if ($check === FALSE)
            {
                return $this->common_response($this->user_verify_service);
            }
            else
            {
                //验证通过之后，把验证码赋给 session
                $this->session->set_userdata($this->_find_pwd_code, $code);
                return $this->common_response(0);
            }
        }
    }

    /**
     * ::找回密码::重置密码
     *（输入格式正确的密码，能够正常修改密码）
     */
    public function reset_password_post()
    {

        //从session中获取账号和途径(type) 1为邮箱，2为手机
        $my_session = $this->session->userdata($this->_find_pwd_user);
        if (empty($my_session))
        {
            return $this->common_response(1008);
        }

        $pwd = trim($this->input->post('password',TRUE));
        $new_pwd_valid=$this->form_validation->new_valid_password($pwd);
        //判断密码是否符合
        if($new_pwd_valid !=0)
        {
            return $this->common_response($new_pwd_valid);
        }
        //判断$my_session获取到的数据是否正确
        if (! isset($my_session['type']) || ! isset($my_session['account']))
        {
            return $this->common_response(1008);
        }

        if ($my_session['type'] == 1)
        {
            //邮箱验证 参数：1，从session中取得验证码。2，获取账号。3，方式
            $check = $this->user_verify_service->check_email_verify_code($this->session->userdata($this->_find_pwd_code), $my_session['account'],User_verify_service::PROCESS_FIND_PASSWORD,FALSE,TRUE);

        }
        else
        {
            $check = $this->user_verify_service->check_sms_code($this->session->userdata($this->_find_pwd_code), $my_session['account'], User_verify_service::PROCESS_FIND_PASSWORD, TRUE);
        }
        //验证不通过，则返回错误代码
        if ($check === FALSE)
        {

            return $this->common_response($this->user_verify_service);
        }
        //如果以上验证码验证通过，则修改数据库里面的密码。
        if ($my_session['type'] == 1)
        {

            $state = $this->user_info_service->update_user_info_by_email($my_session['account'], array('password' => md5($pwd)));
        }
        else if($my_session['type'] == 2)
        {
            $state = $this->user_info_service->update_user_info_by_phone($my_session['account'], array('password' => md5($pwd)));
        }
        //修改通过
        if ($state)
        {
            $this->common_response(0);
        }
        else
        {
            $this->common_response($this->user_verify_service);
        }
    }



    /**
     * ::修改密码
     *
     */
     public  function update_password_put()
     {
         $old_pwd=trim($this->put('password'));
         $new_pwd=trim($this->put('new_password'));

         //判断新旧密码是否相同
         if($old_pwd==$new_pwd)
         {
             return $this->common_response(5017);
         }
         //判断新密码是否符合
         $new_pwd_valid=$this->form_validation->new_valid_password($new_pwd);

         if($new_pwd_valid !=0)
         {
            return $this->common_response($new_pwd_valid);
         }
         //获取登录人的信息
         $old_uin = $this->login_service->reload_user_info();

         //判断$old_pwd是否和数据库一致
         if(md5($old_pwd)!=$old_uin['password'])
         {
             return $this->common_response(5002);
         }
         //var_dump(array($old_uin));exit;
         //修改密码
         $update=$this->user_info_service->update_user_info($old_uin['id'],array('password'=>md5($new_pwd)));
         if(!$update)
         {
             return $this->common_response($this->user_info_service);
         }
         else
         {
             return $this->common_response(0);
         }

     }


}